<template>
  <el-form ref="basicInformationForm" :model="basicInformationForm" label-width="99px" :hide-required-asterisk="true">
    <Form :form="basicInformationForm" :ActivityAreaList="AreaList" :parentPlanName="Originalarray"></Form>
    <el-row style="margin-top: 20px">
      <el-col :span="8">
        <el-form-item label="" prop="remark">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item></el-col>
    </el-row>
  </el-form>
</template>
<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import {
  getLists,
  insertData,
  deletelist,
  ModifierList,
} from "../../api/Genericmethods/GeneralQuery.js";
// import Concretestep from "./concretestep.vue";
import Form from "./components/form.vue";
export default {
  // eslint-disable-next-line vue/no-unused-components
  components: { Form },
  props: {},
  data() {
    return {
      // 表单参数
      basicInformationForm: {
        AccidentArea: "",
        AccidentPoint: "",
        AccidentRisk: "",
        AccidentScope: "",
        AccidentType: "",
        AccidentWarnDeal: "",
        AccidentWarnSign: "",
        Gradename: "",
        Notes: "",
        PlanName: "",
        PlanType: "",
        PossibleEffectScope: "",
        PossibleMatter: "",
        PossibleOccurArea: "",
        PossibleSeverity: "",
        PossibleTime: "",
        Possiblelinkage: "",
        Responselevel: "", //响应等级
      },
      AreaList: [
        {
          zoneofaction: "",
          AccidentArea: "",
          MeasureName: "",
          // 左边的选中状态
          currentDisposal: 0,
          Disposalserialnumber: [
            {
              DealStep: "",
              divContents: [
                {
                  DealExecutor: "",
                  contents: [{ value: "" }],
                },
              ],
            },
          ], // 存储处置信息的数组
        },
      ],
      Originalarray: "",
      newlists: [],
    };
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 获取具体步骤列表
    Listofspecificsteps() {
      getLists("EmergPlan_SiteRspMrs_Deal")
        .then((data) => {
          let array = [];
          for (let index = 0; index < data.length; index++) {
            const element = data[index];
            if (element.PlanName === this.basicInformationForm.PlanName) {
              array.push(element);
            }
          }
          console.log(array);
          const sortedData = array.sort((a, b) => {
            return a.DealCode - b.DealCode;
          });
          this.AreaList = [];

          sortedData.forEach((item) => {
            let activityArea = this.AreaList.find(
              (a) => a.MeasureName === item.MeasureName
            );
            let zoneofaction = ""
            if (item.AccidentArea) {
              zoneofaction = "区域";
            } else if (item.AccidentPoint) {
              zoneofaction = "设备";
            }
            const AccidentArea = item.AccidentArea || item.AccidentPoint;
            if (!activityArea) {
              activityArea = {
                zoneofaction: zoneofaction,
                AccidentArea: AccidentArea,
                MeasureName: item.MeasureName,
                currentDisposal: 0,
                Disposalserialnumber: [],
              };
              this.AreaList.push(activityArea);
            }

            let disposalSerialNumber = activityArea.Disposalserialnumber.find(
              (d) => d.DealStep === item.DealStep
            );
            if (!disposalSerialNumber) {
              disposalSerialNumber = {
                DealStep: item.DealStep,
                divContents: [],
              };
              activityArea.Disposalserialnumber.push(disposalSerialNumber);
            }

            let divContent = {
              DealExecutor: item.DealExecutor,
              contents: [],
            };

            for (let i = 1; i <= 10; i++) {
              let dealContentKey = `DealContent${i}`;
              let dealContentValue = item[dealContentKey] || "";
              if (dealContentValue !== "") {
                divContent.contents.push({ value: dealContentValue });
              }
            }

            disposalSerialNumber.divContents.push(divContent);
          });

          console.log(this.AreaList);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 判断是否一样
    isshows(list, newlist) {
      let filteredArray = list.filter((item) => {
        return item.PlanName === this.$route.query.row.PlanName;
      });
      for (let index = 0; index < filteredArray.length; index++) {
        const element = filteredArray[index];
        this.AreaList = element.AreaList.sort((a, b) => a - b);
      }
      let filteredArrays = newlist.filter((item) => {
        return item.PlanName === this.$route.query.row.PlanName;
      });
      for (let index = 0; index < filteredArrays.length; index++) {
        const element = filteredArrays[index];
        // this.newlists = element.AreaList;
        this.newlists = element.AreaList.sort((a, b) => a - b);
      }
    },
    // 取消按钮
    cancel() {
      this.$router.push("/Onsitedisposalplan");
      this.$refs["basicInformationForm"].resetFields();
    },
    // 提交按钮
    submitForm() {
      this.$refs["basicInformationForm"].validate((valid) => {
        if (valid) {
          const oldPlanName = this.$route.query.row.PlanName;
          let sql = ` "PlanName" ${oldPlanName ? `= '${oldPlanName}'` : "is null"
            }`;
          // console.log(oldPlanName, "旧数组");
          deletelist("EmergPlan_SiteRspMrs_Deal", sql)
            .then((res) => {
              //  console.log(res,"55555");
              //  console.log(res.getAllParams,"删除");
              if (res.data.code === 1) {
                // this.$message.success("删除成功");
              } else {
                this.$message.error(res.data.message);
              }
              this.OperationLog(res, this.$route.meta.title);
            })
            .catch((error) => {
              console.log(error);
            });
          const PlanName = this.basicInformationForm.PlanName;
          const PlanType = this.basicInformationForm.PlanType;
          const AreaList = this.AreaList;
          const sqllist =
            '`PlanType`,`PlanName`,`AccidentArea`,`AccidentPoint`,`DealCode`,`DealStep`,`MeasureName`,`DealExecutor`,`DealContent1`,`DealContent2`,`DealContent3`,`DealContent4`,`DealContent5`,`DealContent6`,`DealContent7`,`DealContent8`,`DealContent9`,`DealContent10`,`DealContent11`,`DealContent12`,`DealContent13`,`DealContent14`,`DealContent15`,`DealContent16`,`DealContent17`,`DealContent18`,`DealContent19`,`DealContent20`';
          const insertSql = [];
          // console.log(this.AreaList);
          for (let i = 0; i < AreaList.length; i++) {
            const area = AreaList[i];
            let AccidentArea = "";
            let AccidentPoint = "";

            if (area.zoneofaction === "设备") {
              AccidentPoint = area.AccidentArea;
            } else if (area.zoneofaction === "区域") {
              AccidentArea = area.AccidentArea;
            }
            for (let j = 0; j < area.Disposalserialnumber.length; j++) {
              const disposal = area.Disposalserialnumber[j];

              for (let k = 0; k < disposal.divContents.length; k++) {
                const content = disposal.divContents[k];

                const dealCode = j + 1;
                // let sql = `INSERT INTO IMP."EmergPlan_SiteRspMrs_Deal" ("PlanType","PlanName","AccidentArea","AccidentPoint","DealCode","DealStep","MeasureName","DealExecutor","DealContent1","DealContent2","DealContent3","DealContent4","DealContent5","DealContent6","DealContent7","DealContent8","DealContent9","DealContent10") VALUES (`;
                let sql = `'${PlanType}','${PlanName}','${AccidentArea}','${AccidentPoint}','${dealCode}','${disposal.DealStep}','${area.MeasureName}','${content.DealExecutor}'`;

                for (let l = 0; l < 20; l++) {
                  const value = content.contents[l]?.value || ""; // 如果值为 undefined 或 null，则设置为空字符串
                  sql += `,'${value}'`;
                }
                insertSql.push(sql);
              }
            }
          }
          // 创建一个空数组，用于存储所有请求的Promise对象
          const promises = [];

          for (let index = 0; index < insertSql.length; index++) {
            const element = insertSql[index];

            // 将每个请求添加到promises数组中
            const promise = insertData(
              "EmergPlan_SiteRspMrs_Deal",
              sqllist,
              element
            )
              .then((res) => {
                if (res.data.code === 1) {
                  this.OperationLog(res, this.$route.meta.title);
                  return res;
                } else {
                  throw new Error(res.data.message);
                }
              })
              .catch((err) => {
                console.log(err);
                throw err;
              });

            promises.push(promise);
          }

          // 使用Promise.allSettled()等待所有请求完成
          Promise.allSettled(promises).then((results) => {
            // 所有请求都完成
            const isSuccess = results.every(
              (result) => result.status === "fulfilled"
            );
            if (isSuccess) {
              this.$router.push("/Onsitedisposalplan");
              this.$modal.msgSuccess("具体步骤修改成功");
            } else {
              // 请求中有一个或多个失败
              const failedResults = results.filter(
                (result) => result.status === "rejected"
              );
              failedResults.forEach((result) => {
                this.$message.error(result.reason.message);
              });
            }
          });
          // 执行修改操作
          const result = Object.entries(this.basicInformationForm)
            .map(([key, value]) => `\`${key}\` = '${value}'`)
            .join(" , ");
          const Originalarray = Object.entries(this.Originalarray)
            .map(([key, value]) => {
              if (value === null) {
                return `\`${key}\` is NULL`;
              } else {
                return `\`${key}\` = '${value}'`;
              }
            })
            .join(" and ");
          ModifierList("EmergPlan_SiteRspMrs", result, Originalarray)
            .then((res) => {
              if (res.data.code === 1) {
                this.$modal.msgSuccess("基本信息修改成功");
              } else {
                this.$message.error(res.data.message);
              }
              this.OperationLog(res, this.$route.meta.title);
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          return this.$message.error(false);
        }
      });
    },
    OperationLog(res, title) {
      // INSERT INTO IMP."OperationLogList" ("timestamp","SQL","TIP","code","message","title") VALUES ('1','2','3','4','6','7')
      const timestamp = "'" + res.data.timestamp + "'";
      const SQL = "'" + res.getAllParams.SQL.replace(/'/g, "\\'") + "'";
      const TIP = "'" + res.getAllParams.TIP + "'";
      const code = "'" + res.data.code + "'";
      const message = "'" + res.data.message + "'";
      const titles = "'" + title + "'";
      const parameter = "OperationLogList";
      const fieldlist = '`timestamp`,`SQL`,`TIP`,`code`,`message`,`title`';
      const result = `${timestamp}, ${SQL}, ${TIP}, ${code}, ${message}, ${titles}`;
      insertData(parameter, fieldlist, result).catch((err) => {
        console.log(err, "操作日志");
      });
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.basicInformationForm = { ...this.$route.query.row };
    this.Originalarray = this.$route.query.row;
    // 事故类型
    if (this.$route.query.row.AccidentType !== null || "") {
      let accidentTypesArray;
      if (this.$route.query.row.AccidentType.includes(",")) {
        // 判断是否包含逗号，即是否有多个事故类型
        accidentTypesArray = this.$route.query.row.AccidentType.split(",");
      } else {
        accidentTypesArray = [this.$route.query.row.AccidentType]; // 如果只有一个事故类型，直接将其组成数组
      }
      this.basicInformationForm.AccidentType = accidentTypesArray;
    }
    // 可能联动范围
    if (this.$route.query.row.Possiblelinkage !== null || "") {
      let accidentTypesArray;
      if (this.$route.query.row.Possiblelinkage.includes(",")) {
        // 判断是否包含逗号，即是否有多个事故类型
        accidentTypesArray = this.$route.query.row.Possiblelinkage.split(",");
      } else {
        accidentTypesArray = [this.$route.query.row.Possiblelinkage]; // 如果只有一个事故类型，直接将其组成数组
      }
      this.basicInformationForm.Possiblelinkage = accidentTypesArray;
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.Listofspecificsteps();
  },
  beforeCreate() { }, // 生命周期 - 创建之前
  beforeMount() { }, // 生命周期 - 挂载之前
  beforeUpdate() { }, // 生命周期 - 更新之前
  updated() { }, // 生命周期 - 更新之后
  beforeDestroy() { }, // 生命周期 - 销毁之前
  destroyed() { }, // 生命周期 - 销毁完成
  activated() { }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="scss" scoped>
.box-card {
  margin-top: 3%;
}

::v-deep .el-form-item__label {
  text-align: left;
}

.IsMust {
  position: absolute;
  color: #f56c6c;
  // 位置可以根据自己的样式自行调整
  top: -4px;
  left: -38px;
}
</style>
